package pkg

import (
	"fmt"
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func OssUpload(filename, url string) (string, error) {
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("cn-shanghai"))
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("https://oss-cn-shanghai.aliyuncs.com", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}
	bucketName := "22083" // 请替换为实际的Bucket名称
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket: %v", err)
	}
	objectKey := filename                 // 请替换为实际的对象Key
	localFilePath := url + "/" + filename // 请替换为实际的本地文件路径
	err = bucket.PutObjectFromFile(objectKey, localFilePath)
	if err != nil {
		log.Fatalf("Failed to put object from file: %v", err)
	}
	log.Println("File uploaded successfully.")
	fileUrl := fmt.Sprintf("https://%s.oss-cn-shanghai.aliyuncs.com/%s", bucketName, objectKey)
	return fileUrl, err
}
